package com.cn.netty.basic;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

@Slf4j
public class EchoServerHandler extends
//        SimpleChannelInboundHandler
        ChannelInboundHandlerAdapter {

  @Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    try {
      ByteBuf buf = (ByteBuf) msg;
      log.info("request {}", buf.toString(StandardCharsets.UTF_8));
      for (int i = 0; i < 2; i++) {
        //可以并发调用。因为 会使用channel 或者 Handler 上绑定的EventLoop线程去处理事件。
        new Thread(new Runnable() {
          @Override
          public void run() {
            ChannelFuture channelFuture = ctx.channel().writeAndFlush(
                    Unpooled.copiedBuffer(
                            ("i`m server " + System.currentTimeMillis() + EchoServer.property).getBytes(StandardCharsets.UTF_8))
            );
            channelFuture.addListener(new GenericFutureListener<Future<? super Void>>() {
              @Override
              public void operationComplete(Future<? super Void> future) throws Exception {
                log.info("wirte finish -> {}", future.get());
              }
            });
          }
        }).start();
//        ChannelFuture channelFuture = ctx.channel().writeAndFlush(
//                Unpooled.copiedBuffer(
//                        ("i`m server " + System.currentTimeMillis() + EchoServer.property).getBytes(StandardCharsets.UTF_8))
//        );
//        channelFuture.addListener(new GenericFutureListener<Future<? super Void>>() {
//          @Override
//          public void operationComplete(Future<? super Void> future) throws Exception {
//              log.info("wirte finish -> {}",future.get());
//          }
//        });

      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      ReferenceCountUtil.release(msg);
    }
  }

  @Override
  public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
    log.info("channelReadComplete");
  }

  @Override
  public void channelActive(ChannelHandlerContext ctx) throws Exception {
    log.info("channelActive");
    super.channelActive(ctx);
  }

}
